/**
 * 用户中心
 */
$(function() {
	
	// 绑定事件
	$(window).on("load", queryUserInfo);
	// $(window).on("load", getLocation);
	//$('.personaldoctors').on("touchstart", enterMyDoctor);
	//$('.personalsheets').on("touchstart", enterMyPrescribe);
	//$('.personalservice').on("touchstart", enterMyService);
	//$('.accountBtn').on("touchstart", enterMyAccount);
	//$('.scanBtn').on("touchstart", scanQRCode);
	$('.electronicArchives').on("touchstart", electronicArchives);
	
	//获取ApiSign
	function initGetJsApiSign(url) {
		var params = {
			"url" : url
		};
		userCenterModule.getJsApiSign(params, function(callback) {
			var info = callback;
			if (info != null) {
				wx.config({
					debug : false, // 开启调试模式
					appId : info.appId,
					timestamp : info.timestamp, // 必填，生成签名的时间戳
					nonceStr : info.nonceStr, // 必填，生成签名的随机串
					signature : info.signature, // 必填，签名，见附录1
					jsApiList : [ 'scanQRCode', 'getLocation']
				});
			}
		});
	}

	// 获取个人资料信息
	function queryUserInfo() {
		var nickname = utilModule.getStorage("nickname"),
		nickname = decodeURIComponent(nickname);
		var avatar = utilModule.getStorage("avatar");
		var params = {
			"userid": USERID
		};
		userCenterModule.queryUserInfo(params, function(callBack) {
			console.log(callBack);
			var userInfo = callBack;
		    var nickname = decodeURIComponent(userInfo.nickname);
			var avatar = userInfo.avatar;
			utilModule.setStorage("nickname", nickname);
			utilModule.setStorage("avatar", avatar);
			utilModule.setStorage("userim", userInfo.usernameim);
		});
			$(".personalheader-doctor").html(nickname);
			$(".header-cls").attr("src",avatar);
		
		initGetJsApiSign("n/html/userCenter/user-center.html");
		
	}

	/**
	 * 获取地理位置
	 */
	function getLocation(){
		initGetJsApiSign("n/html/prescription/prescription-wechat.html");
		wx.getLocation({
	    	success: function(res) {
		        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
		        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
		        //去数据库查询获取附近的门店
	            utilModule.post({
	                url: "userCenter/queryDetail",
	                data: {"latitude":latitude,"longitude":longitude},
	                needJson: false, 
	                async: false,
	                success: function (response) {
	                    if(response.status==200){
	                    	console.log(response.result);
	                    	var url = "http://apis.map.qq.com/tools/poimarker?type=0&marker=coord:"+result.lat+","+result.lon+";title:"+result.lon+";addr:"+result.lon+"&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=myappr=myapp"
	                    	$("#bind_url").attr("url",url);
	                    }
	                }
	            });
			}
		});
		wx.error(function(res) {
			alert("返回结果：" + res.errMsg);
		});
	}
	/**
	 * 扫描二维码
	 */
	wx.ready(function() {
		$('.scanBtn').on("click", function(){
     	    wx.scanQRCode({
				needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
				scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
				success: function(res) { 
					var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
					if(result.indexOf("doctorid")!=-1){ 
					   var indx=result.indexOf("="); 
					   var  doctorId=result.substr(indx+1);
					   addDoctorFirend(doctorId);
					}else{
						mui.alert("请扫描医生端提供的二维码!","提示");
						return false;
					}
				}
			});
		});
	});
 
	/**
	 * 添加醫生好友
	 * @returns
	 */
	function addDoctorFirend(_doctorid){
	    console.log("doctorid:"+_doctorid);
	    var params={};
	    params.doctorid=_doctorid;
	    params.patientid=USERID;
	    
	     //判断该医生是否真实存在
	    var doctorInfo=queryDoctorInfo(_doctorid);
	    if(doctorInfo==null){
	        mui.alert("关注失败，二维码可能已失效！","提示");	
	        return false;
	    }else{
		    userCenterModule.addDoctorFirend(params, function(callBack) {
		    	var result=callBack;
		    	if(result.status==200){
		    	    mui.alert("恭喜您成功扫描"+doctorInfo.realname+"医生为您的专属医生!","提示",function(){
		    		    location.replace("../../index.html");
		    		   /*location.replace("../doctor/doctor-details.html?doctorid="+_doctorid);*/
		    	    });
		    	}else{
		    	   mui.alert(result.msg,"提示");
		    	}
			});
		}
	}
	
	
		  /**
   * 获取医生详情
   * @param {Object} $doctorid
   */
   function queryDoctorInfo($doctorid){
  	 var params = {
		"doctorId": $doctorid
	};
	var doctorInfo=null;
	utilModule.post({
		url: "doctor/doctorDetail",  //医生详情页
		data: params,
		needJson: false,
		async: false,
		success: function(response) {
			console.log(response);
			var result = response;
			if(result != null) {
				  doctorInfo = result.doctor;
			}
		}
	});
	return doctorInfo;
  }
	
	$(".html-loding").hide();
	
	function enterMyDoctor() {
		location.href = "../doctor/my-doctor.html"; // 我的医生
	}

	function enterMyPrescribe() {
		location.href="../prescription/prescription-sheet.html" // 我的处方单
	}

	function enterMyService() {
		location.href = 'services.html?v=1.1.0'; // 我的服务
	}

	function enterMyAccount() {
		location.href = "user-balance.html"; // 我的账户
	}
	function electronicArchives() {           //USERID
		var param = {"patientid":USERID,"type":2};
		function callBack(data){
			console.log(data);
			if(data==null){       //电子档案
				location.href = "../../html/electronicArchives/add-record.html"
			}else{
				sessionStorage.setItem("skipType","4");
				location.href = "../../html/service/user-archives-list.html"
			}
		}
		archivesModule.loadMyArchives(param,callBack);
		//electronicArchivesMdule.queryElectronicArchivesList(param,callBack);
	}

	document.getElementById('index').addEventListener('tap',function(){
		mui.openWindow({
			url:'../../index.html',
    		id:'index',
		});
	});
	document.getElementById('message').addEventListener('tap',function(){
		mui.openWindow({
			url:'../../html/inquiry/message-list.html',
    		id:'message',
		});
	});
	document.getElementById('article').addEventListener('tap',function(){
		mui.openWindow({
			url:'../../html/article/article-list.html',
    		id:'article',
		});
	});
	document.getElementById('userCenter').addEventListener('tap',function(){
		mui.openWindow({
			url:'../../html/userCenter/user-center.html',
    		id:'userCenter',
		});
	});
	
	$('.order-form li').on('click',function(){
		var typeOf=$(this).attr("v");
		location.href ='../../html/onlineContinuation/my-order.html?shipping_status='+typeOf;
	});
});